package com.lxinet.jeesns.core.utils;

import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class DES3Util
{
  private static String prikey = "$%^#@$%^&&^%jeesns.cn%$@#$%^%()*";
  
  public static String des3EncodeECB(String val)
    throws Exception
  {
    byte[] key = new BASE64Decoder().decodeBuffer(prikey);
    byte[] data = val.getBytes("UTF-8");
    DESedeKeySpec spec = new DESedeKeySpec(key);
    SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
    Key deskey = keyfactory.generateSecret(spec);
    Cipher cipher = Cipher.getInstance("desede/ECB/PKCS5Padding");
    cipher.init(1, deskey);
    byte[] bOut = cipher.doFinal(data);
    return new BASE64Encoder().encode(bOut);
  }
  
  public static String des3DecodeECB(String val)
    throws Exception
  {
    byte[] data = new BASE64Decoder().decodeBuffer(val);
    
    byte[] key = new BASE64Decoder().decodeBuffer(prikey);
    DESedeKeySpec spec = new DESedeKeySpec(key);
    SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
    Key deskey = keyfactory.generateSecret(spec);
    Cipher cipher = Cipher.getInstance("desede/ECB/PKCS5Padding");
    cipher.init(2, deskey);
    byte[] bOut = cipher.doFinal(data);
    return new String(bOut, "UTF-8");
  }
}
